package com.pay.game.central.config;

import com.alibaba.fastjson.JSON;
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.pay.game.central.common.Result;
import com.pay.game.central.common.ResultCode;
import com.pay.game.central.security.annotaion.PassToken;
import com.pay.game.central.security.annotaion.UserLoginToken;
import com.pay.game.central.system.bean.User;
import com.pay.game.central.system.service.UserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.Method;

public class AuthenticationInterceptor implements HandlerInterceptor {

    private final Logger logger = LoggerFactory.getLogger(AuthenticationInterceptor.class);

    @Autowired
    UserService userService;

    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object object) throws Exception {
        String token = httpServletRequest.getHeader("X-Token");// 从 http 请求头中取出 token
        // 如果不是映射到方法直接通过
        if (!(object instanceof HandlerMethod)) {
            return true;
        }
        HandlerMethod handlerMethod = (HandlerMethod) object;
        Method method = handlerMethod.getMethod();
        //检查是否有passtoken注释，有则跳过认证
        if (method.isAnnotationPresent(PassToken.class)) {
            PassToken passToken = method.getAnnotation(PassToken.class);
            if (passToken.required()) {
                return true;
            }
        }
        //检查有没有需要用户权限的注解
        if (method.isAnnotationPresent(UserLoginToken.class)) {
            UserLoginToken userLoginToken = method.getAnnotation(UserLoginToken.class);
            if (userLoginToken.required()) {
                // 执行认证
                if (token == null) {
                    logger.warn("签名认证失败(未携带token)，请求接口：{}，请求IP：{}，请求参数：{}",
                            httpServletRequest.getRequestURI(), getIpAddress(httpServletRequest), JSON.toJSONString(httpServletRequest.getParameterMap()));
                    Result result = new Result();
                    result.setCode(ResultCode.ILLEGAL_TOKEN).setMessage("请求未携带token");
                    responseResult(httpServletResponse, result);
                    return false;
                }
                // 获取 token 中的 user id
                DecodedJWT jwt;
                try {
                    jwt = JWT.decode(token);
                } catch (JWTDecodeException j) {
                    logger.warn("签名认证失败(jwt验证失败)，请求接口：{}，请求IP：{}，请求参数：{}",
                            httpServletRequest.getRequestURI(), getIpAddress(httpServletRequest), JSON.toJSONString(httpServletRequest.getParameterMap()));
                    Result result = new Result();
                    result.setCode(ResultCode.ILLEGAL_TOKEN).setMessage("签名认证失败");
                    responseResult(httpServletResponse, result);
                    return false;
                }
                if(jwt.getExpiresAt().getTime() < System.currentTimeMillis()){
                    Result result = new Result();
                    result.setCode(ResultCode.EXPIRED_TOKEN).setMessage("签名过期");
                    responseResult(httpServletResponse, result);
                    return false;
                }
                String userId = jwt.getAudience().get(0);
                User user = userService.geValidateInfoById(userId);
                if (user == null) {
                    logger.warn("签名认证失败(用户不存在)，请求接口：{}，请求IP：{}，请求参数：{}",
                            httpServletRequest.getRequestURI(), getIpAddress(httpServletRequest), JSON.toJSONString(httpServletRequest.getParameterMap()));
                    Result result = new Result();
                    result.setCode(ResultCode.ILLEGAL_TOKEN).setMessage("用户不存在");
                    responseResult(httpServletResponse, result);
                    return false;
                }
                // 验证 token
                JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256(user.getPassword())).build();
                try {
                    jwtVerifier.verify(token);
                } catch (JWTVerificationException e) {
                    logger.warn("签名认证失败(jwt算法验证失败)，请求接口：{}，请求IP：{}，请求参数：{}",
                            httpServletRequest.getRequestURI(), getIpAddress(httpServletRequest), JSON.toJSONString(httpServletRequest.getParameterMap()));
                    Result result = new Result();
                    result.setCode(ResultCode.UNAUTHORIZED).setMessage("签名认证失败");
                    responseResult(httpServletResponse, result);
                    return false;
                }
                return true;
            }
        }
        return true;
    }

    private void responseResult(HttpServletResponse response, Result result) {
        response.setCharacterEncoding("UTF-8");
        response.setHeader("Content-type", "application/json;charset=UTF-8");
        response.setStatus(200);
        try {
            response.getWriter().write(JSON.toJSONString(result));
        } catch (IOException ex) {
            logger.error(ex.getMessage());
        }
    }
    private String getIpAddress(HttpServletRequest request) {
        String ip = request.getHeader("x-forwarded-for");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_CLIENT_IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_X_FORWARDED_FOR");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        // 如果是多级代理，那么取第一个ip为客户端ip
        if (ip != null && ip.indexOf(",") != -1) {
            ip = ip.substring(0, ip.indexOf(",")).trim();
        }

        return ip;
    }
}